// device.h
#ifndef DEVICE_H
#define DEVICE_H

#include <stdint.h>
#include <stdbool.h>

#ifdef __cplusplus
extern "C" {
#endif

struct device;

/* 设备配置结构 */
struct device_config {
    const char *name;
    int (*init)(struct device *dev);
    const void *config_info;
};

/* 设备结构 */
struct device {
    const struct device_config *config;
    const void *driver_api;
    void *driver_data;
};

/* 初始化级别定义 */
typedef enum {
    PRE_KERNEL_1 = 0,
    PRE_KERNEL_2,
    POST_KERNEL,
    APPLICATION,
    INIT_LEVEL_COUNT
} init_level_t;

/* 设备注册信息结构 */
struct device_registry {
    struct device *dev;         // 设备指针
    init_level_t init_level;    // 初始化级别
    uint8_t init_priority;      // 初始化优先级(0-99)
    bool initialized;           // 初始化状态
    struct device_registry *next;
};

typedef void (*device_register_t)(void);

/* 设备注册接口 */
#define DEVICE_DEFINE(_name, _drv_name, _init_fn, _config_info, _driver_api, _driver_data, _level, _prio) \
    static const struct device_config _name##_config = { \
        .name = _drv_name, \
        .init = _init_fn, \
        .config_info = _config_info \
    }; \
    static const struct device _name##_device = { \
        .config = &_name##_config, \
        .driver_api = _driver_api, \
        .driver_data = _driver_data \
    }; \
    void _name##_register(void) { \
        device_register(&_name##_device, _level, _prio); \
    }

#define EXTERN_DEVICE_REGISTER(_name) \
    extern void _name##_register(void); \

#define DEVICE_REGISTER(_name) \
    _name##_register

/* 系统初始化接口 */
void device_init(void);

/* 设备查找接口 */
struct device *device_get_binding(const char *name);

/* 内部注册函数 */
void device_register(const struct device *dev, init_level_t level, uint8_t priority);

#ifdef __cplusplus
}
#endif

#endif // DEVICE_H
